import http from './http'

export const STATUS_LABEL_BY_CODE = {
  1: '正常',
  0: '停用',
}

const API = {
  base: '/users',
  list: '/users',
  add: '/users',
  remove: (ids) => `/users/${ids}`,
  getById: (id) => `/users/${id}`,
}

function normalizeItem(item) {
  const createTime = item.createTime || item.create_time
  const updateTime = item.updateTime || item.update_time
  return {
    id: item.id,
    username: item.username,
    name: item.name,
    phone: item.phone,
    email: item.email,
    gender: item.gender,
    status: item.status,
    statusLabel: STATUS_LABEL_BY_CODE?.[item.status] ?? '',
    deptId: item.deptId,
    roleId: item.roleId,
    image: item.image,
    remark: item.remark,
    createTime,
    updateTime,
    deptName: item.deptName,
    roleName: item.roleName,
  }
}

// 修复：http.js 在 code===1 时已返回 r.data，因此这里不再使用 res.data.data
// 兼容两种后端返回：
// 1) { rows: [], total: N }
// 2) 直接返回数组 [] （不分页）
export async function listUsers(params = {}) {
  const raw = await http.get(API.list, { params })
  let rows = []
  let total = 0
  if (raw && typeof raw === 'object') {
    if (Array.isArray(raw.rows)) {
      rows = raw.rows
      total = Number(raw.total ?? rows.length) || rows.length
    } else if (Array.isArray(raw.list)) {
      rows = raw.list
      total = Number(raw.total ?? rows.length) || rows.length
    } else if (Array.isArray(raw)) {
      rows = raw
      total = raw.length
    }
  } else if (Array.isArray(raw)) {
    rows = raw
    total = raw.length
  }
  return { total, rows: rows.map(normalizeItem) }
}

export async function addUser(payload) {
  return await http.post(API.add, payload)
}

export async function removeUsers(idsCsv) {
  return await http.delete(API.remove(idsCsv))
}

export async function getUserById(id) {
  const raw = await http.get(API.getById(id))
  const item = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : null
  return item ? normalizeItem(item) : null
}
